package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import pojo.Book;
import pojo.Orders;
import pojo.User;
import service.BookManager;
import service.impl.BookmanagerFactory;
import util.DButil;

/**
 * Servlet implementation class AddToCar
 */
public class AddToCar extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BookManager manager;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddToCar() {
        super();
        manager=BookmanagerFactory.getInstance();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		boolean find=true;
		User u=(User)request.getSession().getAttribute("user");
		int bid=Integer.parseInt(request.getParameter("id"));
		HashSet<Orders> oSet=(HashSet<Orders>)request.getSession().getAttribute("oset");
		DataSource ds=(DataSource)request.getServletContext().getAttribute("ds");
		Connection con=DButil.getConnection(ds);
		Book book=manager.getBook(bid, con);
		
		
		if (!oSet.isEmpty()) {
			for (Orders o:oSet) {
				if (book.getName().equals(o.getbName())) {
					o.setCount(o.getCount()+1);
					find=true;
				}else {
					find=false;
				}
			}
			if (!find) {
				Orders orders =new Orders();
				orders.setbName(book.getName());
				orders.setuName(u.getName());
				orders.setBuyDate(new Date());
				orders.setCount(1);
				oSet.add(orders);
			}			
		}else {
			Orders orders =new Orders();
			orders.setbName(book.getName());
			orders.setuName(u.getName());
			orders.setBuyDate(new Date());
			orders.setCount(1);
			oSet.add(orders);
		}

		
		request.getSession().setAttribute("oset", oSet);
		request.getRequestDispatcher("shoppingcar.jsp").forward(request, response);
		DButil.close(con);		
	}


	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
